<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共166条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <!-- checkPermission 是一个校验函数, 传入一个按钮名称
          可以根据当前用户数据返回是否有权限的 true / false -->
          <el-button :disabled="!checkPermission('exportEmployee')" size="small" type="danger" @click="exportExcel">导出</el-button>
          <el-button :disabled="!checkPermission('addEmployee')" size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="employeeList">

          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" sortable="" width="200">
            <template #default="{row}">
              <img v-imgerr="require('@/assets/common/head.jpg')" :src="row.staffPhoto" alt="" class="avatar" @click="showAvatar(row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="">
            <template #default="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="">
            <template #default="{row}">
              <el-switch
                :value="row.enableState === 1"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :page-size="page.size"
            :total="page.total"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <AddEmployee :show-dialog="showDialog" />

      <el-dialog title="头像" :visible="isShowAvatar">
        <el-row type="flex" justify="center">
          <canvas ref="myAvatar" />
        </el-row>
      </el-dialog>

      <assign-role
        ref="assignRole"
        :show-dialog.sync="showAssignRole"
        :user-id="userId"
      />
    </div>
  </div>
</template>

<script>
import { getEmployee, delEmployee } from '@/api/employees'
import employeeEnum from '@/api/constant/employees'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import { formatDate } from '@/filters'
import AddEmployee from './components/add-employee.vue'
import QRCode from 'qrcode'
import AssignRole from './components/assign-role.vue'
export default {
  // filters: {
  //   formatDate(old) {
  //     // console.log('过滤器的this', this)
  //     // 过滤器没有 this
  //     return old.split('T')[0]
  //   }
  // },
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      page: {
        page: 1,
        size: 5,
        total: 0
      },
      employeeList: [],
      showDialog: false,
      isShowAvatar: false,
      showAssignRole: false,
      userId: ''
    }
  },
  created() {
    this.getEmployee()
  },
  methods: {
    async assignRole(id) {
      // 获取旧数据
      await this.$refs.assignRole.getCheckedRole(id)
      // 临时保存当前点击的员工
      this.userId = id
      this.showAssignRole = true
    },
    async exportExcel() {
      // 拿到全部员工数据
      const { rows } = await getEmployee({ page: 1, size: this.page.total })
      console.log(rows)
      // 根据生成 excel 插件需要, 转换数据
      const header = [
        '手机号',
        '姓名',
        '入职日期',
        '聘用形式',
        '转正日期',
        '工号',
        '部门'
      ]
      const data = rows.map(userObj => {
        return this.obj2arr(userObj, header)
      })
      console.log(rows)
      console.log(data)
      // 导出
      export_json_to_excel({
        header,
        data
      })
    },
    obj2arr(userObj, header) {
      const userArr = []
      // 将用户对象里面的数据
      // 按照表头的顺序, 逐个放入到数组中
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      header.forEach(key => {
        const enKey = dict['key']
        let value = userObj[enKey]
        if (enKey === 'formOfEmployment') {
          // 如果是聘用形式, 用枚举数据处理
          const obj = employeeEnum.hireType.find(item => item.id === value)
          value = obj ? obj.value : '未知形式'
        }
        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          // 格式化日期
          value = formatDate(value)
        }
        userArr.push(value)
      })
      return userArr
    },
    async getEmployee() {
      const { rows, total } = await getEmployee(this.page)
      // 这里是拿到了用户数据, 有个小 bug
      // 本地数据库缺少了 enableState 数据
      // 线上是有的, 临时用短路运算填一个默认值, 方便测试
      this.employeeList = rows.map(user => {
        return {
          ...user,
          enableState: user.enableState || 1
        }
      })
      this.page.total = total
    },
    currentChange(newPage) {
      this.page.page = newPage
      this.getEmployee()
    },
    formatEmployment(row, column, cell, index) {
      // 枚举数据, 将所有可能性列举出来

      // 要拿值的时候, 只需要, 查找当前的数组中 id === cell 那个对象
      // 输出 value 即可
      const obj = employeeEnum.hireType.find(item => item.id === cell)
      return obj ? obj.value : '未知'
      // if (cell === 1) {
      //   return '正式工'
      // }
      // if (cell === 2) {
      //   return '临时工'
      // }
      // return '未知'
    },
    async delEmployee(id) {
      // 询问
      await this.$confirm(this.$t('questions.delEmployee'))
      // 发请求
      await delEmployee(id)
      // 提示用户
      this.$message.success('删除成功')
      // 更新页面
      this.getEmployee()
    },
    showAvatar(url) {
      if (url) {
        this.isShowAvatar = true

        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.myAvatar, url, {
            width: 300,
            color: {
              dark: '#66b1ff'
            }
          })
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar {
  width: 178px;
  height: 140px;
  object-fit: cover;
}
</style>
